package com.glorystone.ins.controller;

import com.glorystone.ins.common.AesEncryptUtil;
import com.glorystone.ins.common.JsonResult;
import com.glorystone.ins.domain.SysUser;
import com.glorystone.ins.shiro.DisabledException;
import com.glorystone.ins.shiro.IncorrectCaptchaException;

import redis.clients.jedis.Jedis;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录操作
 */
@Controller
public class LoginController {

	private static final Logger log = LoggerFactory.getLogger("LoginController");
	
    @Autowired
    private DefaultWebSessionManager sessionManager;
    @Value("${errorTimes}")
    private Integer errorTimes;
    @Value("${redis.host}")
    private String redisHost;
    @Value("${redis.port}")
    private Integer redisPort;
    @Value("${redis.timeout}")
    private Integer timeOut;

    /**
     * 登录页面
     *
     * @return
     */
    @RequestMapping("index")
    public String index() {
        return "login";
    }

    /**
     *
     */
    @RequestMapping("main")
    public String main(RedirectAttributes model) {
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        int type = user.getType();
        String view;
        if (type == 0) {
            // 内部用户
            view = "redirect:/task/tolist";

        } else if (type == 1) {
            // 外部用户，渠道首页
            view = "redirect:/channel/home";

        } else {

            view = "main";

        }
        return view;
    }

    /**
     * 登出 跳转到主页面
     *
     * @return
     */
    @RequestMapping("logout")
    public String logout() {
        System.out.println(1111111);
        SecurityUtils.getSubject().logout();
        return "redirect:/index";
    }

    /**
     *
     */
    @SuppressWarnings("unused")
	@RequestMapping("dologin")
    public String dologin(HttpServletRequest request,Model mode) {

        String loginFailure = (String) request.getAttribute("shiroLoginFailure");
        JsonResult loginMessage=new JsonResult();
        SysUser user=new SysUser();
        //可以在这里放 错误信息  从这里就可以拿到认证异常了
        if (loginFailure != null) {
            String jobNumber = WebUtils.getCleanParam(request,"username");
            String password = WebUtils.getCleanParam(request,"password");
            try {
                password = AesEncryptUtil.desEncrypt(password).trim();
            } catch (Exception e) {
                e.printStackTrace();
            }
             user.setJobNumber(jobNumber);
             user.setPassword(password);
             mode.addAttribute("user",user);
          if (UnknownAccountException.class.getName().equals(loginFailure)) {  
        	  loginMessage.setMsg("暂无此账户");        	  
        	  mode.addAttribute("loginMessage", loginMessage);
        	  return "forward:/index";
          }else if(DisabledException.class.getName().equals(loginFailure)){
        	  loginMessage.setMsg("该账户暂不可用!");        	  
        	  mode.addAttribute("loginMessage", loginMessage);
        	  return "forward:/index";
          }else if (IncorrectCredentialsException.class.getName().equals(loginFailure)) {                    
        	  	Jedis jedis = new Jedis(redisHost,redisPort,timeOut);
          		try{
          			String Uservalue = jedis.get(jobNumber+"Count");
          			if(Uservalue==null || Uservalue==""){
          				jedis.set(jobNumber+"Count", "1");
          				jedis.expire(jobNumber+"Count", 1800);
          			}else{
          				if(Integer.parseInt(Uservalue)==errorTimes){
          					loginMessage.setMsg("该账户已被锁定,请稍后再登录");
          					mode.addAttribute("loginMessage", loginMessage);
              				return "forward:/index";
              		}
          				Long ttl = jedis.ttl(jobNumber+"Count");
          				jedis.set(jobNumber+"Count", String.valueOf(jedis.incr(jobNumber+"Count")));
          				jedis.expire(jobNumber+"Count", Integer.parseInt(String.valueOf(ttl)));
          			}
          			}catch(Exception e){
          				log.info("------增加错误次数失败-------",jobNumber+"Count",e);
          			}finally{
          				jedis.close();
          			}
          				loginMessage.setMsg("用户名或密码不正确");
          				mode.addAttribute("loginMessage", loginMessage);
          				return "forward:/index";
          }else if(IncorrectCaptchaException.class.getName().equals(loginFailure)){  
        	  loginMessage.setMsg("验证码不正确");
        	  mode.addAttribute("loginMessage", loginMessage);
        	  return "forward:/index"; 
          }else if(LockedAccountException.class.getName().equals(loginFailure)){
        	  loginMessage.setMsg("该账号已被删除,详情请联系管理员");
        	  mode.addAttribute("loginMessage", loginMessage);
        	  return "forward:/index";
          }else {  
        	  loginMessage.setMsg("未知错误");
        	  mode.addAttribute("loginMessage",loginMessage);
        	  return "forward:/index";    
          }         
       }     
        return "redirect:/main";
    }
}
